package com.ruoyi.basebill.controller;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.basebill.domain.WfzWebservice;
import com.ruoyi.basebill.service.IWfzWebserviceService;
import com.ruoyi.basebill.service.impl.billIssue.util.BillIssueUtil;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.webServiceUtil.WSWfzHrztFacadeSrvProxy;
import com.ruoyi.webServiceUtil.WSWfzHrztFacadeSrvProxyServiceLocator;
import com.ruoyi.webServiceUtil.WebServiceHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.axis.client.Stub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basebill.domain.WfzSbft;
import com.ruoyi.basebill.service.IWfzSbftService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 社保分摊Controller
 * 
 * @author ruoyi
 * @date 2022-12-17
 */
@Api(description = "社保分摊")
@RestController
@RequestMapping("/basebill/sbft")
public class WfzSbftController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    @Autowired
    private IWfzSbftService wfzSbftService;

    @Autowired
    private IWfzWebserviceService wfzWebserviceService;

    @Autowired
    private BillIssueUtil billIssueUtil;



    /**
     * 查询社保分摊列表
     */
    @PreAuthorize("@ss.hasPermi('basebill:sbft:list')")
    @GetMapping("/list")
    public TableDataInfo list(WfzSbft wfzSbft)
    {
        startPage();
        List<WfzSbft> list = wfzSbftService.selectWfzSbftList(wfzSbft);
        return getDataTable(list);
    }

    /**
     * 导出社保分摊列表
     */
    @PreAuthorize("@ss.hasPermi('basebill:sbft:export')")
    @Log(title = "社保分摊", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WfzSbft wfzSbft)
    {
        List<WfzSbft> list = wfzSbftService.selectWfzSbftList(wfzSbft);
        ExcelUtil<WfzSbft> util = new ExcelUtil<WfzSbft>(WfzSbft.class);
        util.exportExcel(response, list, "社保分摊数据");
    }

    /**
     * 获取社保分摊详细信息
     */
    @PreAuthorize("@ss.hasPermi('basebill:sbft:query')")
    @GetMapping(value = "/{fid}")
    public AjaxResult getInfo(@PathVariable("fid") Long fid)
    {
        return success(wfzSbftService.selectWfzSbftByFid(fid));
    }

    /**
     * 获取流水号
     */
    @ApiOperation("获取流水号")
    @GetMapping(value = "/getFNumber")
    public AjaxResult getFNumber(){
        WfzSbft wfzSbft = new WfzSbft();
        billIssueUtil.setBillNumber(wfzSbft);
        return success((Object) wfzSbft.getFnumber());
    }

    /**
     * 新增社保分摊
     */
    @PreAuthorize("@ss.hasPermi('basebill:sbft:add')")
    @Log(title = "社保分摊", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WfzSbft wfzSbft)
    {
        wfzSbft.setFcreator(getUsername());
        wfzSbft.setFlastupdateuser(getUsername());
        return toAjax(wfzSbftService.insertWfzSbft(wfzSbft));
    }

    /**
     * 修改社保分摊
     */
    @PreAuthorize("@ss.hasPermi('basebill:sbft:edit')")
    @Log(title = "社保分摊", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WfzSbft wfzSbft)
    {
        wfzSbft.setFlastupdateuser(getUsername());
        wfzSbft.setFlastupdatetime(new Date());
        return toAjax(wfzSbftService.updateWfzSbft(wfzSbft));
    }

    /**
     * 删除社保分摊
     */
    @PreAuthorize("@ss.hasPermi('basebill:sbft:remove')")
    @Log(title = "社保分摊", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fids}")
    public AjaxResult remove(@PathVariable Long[] fids)
    {
        return toAjax(wfzSbftService.deleteWfzSbftByFids(fids));
    }

    /**
     * 调用webService接口
     */
    @ApiOperation("EAS接口调用")
    @GetMapping(value = "/importSbft/{fids}")
    public AjaxResult importSbft(@PathVariable Long[] fids){
        StringBuffer buffer = new StringBuffer();
        //准备两个参数：分别用来记录成功的调用条数，和失败的调用条数
        int succNum = 0;
        int failNum = 0;
        WfzWebservice wfzWebservice = new WfzWebservice();
        wfzWebservice.setJknumber("EAS001");
        List<WfzWebservice> wfzWebservices = wfzWebserviceService.selectWfzWebserviceList(wfzWebservice);
        wfzWebservice= wfzWebservices.get(0);

        String jkpassword = wfzWebservice.getJkpassword(); //密码
        String jkinurl = wfzWebservice.getJkinurl(); //业务接口
        String dcname = wfzWebservice.getDcname(); //数据中心名称
        String jkurl = wfzWebservice.getJkurl(); //登录接口
        String jkmethod = wfzWebservice.getJkmethod(); //业务方法
        String jkusername = wfzWebservice.getJkusername(); //接口用户

        for (int i = 0; i < fids.length; i++) {
            Long fid = fids[i];

            //获取社保缴纳的详细信息
            WfzSbft wfzSbft = wfzSbftService.selectWfzSbftByFid(fid);
            String json = wfzSbftService.importSbft(wfzSbft);
            log.info("社保分摊同步到eas："+json);
            try {
                String login = WebServiceHelper.login(jkusername, jkpassword, jkurl, dcname);
//                String result = WebServiceHelper.serviceInterface(login, jkinurl, jkmethod, json, "WFZ002");
                URL url = new URL(jkinurl);
                WSWfzHrztFacadeSrvProxy wsWfzHrztFacade = new WSWfzHrztFacadeSrvProxyServiceLocator().getWSWfzHrztFacade(url);
                ((Stub) wsWfzHrztFacade).setHeader("http://login.webservice.bos.kingdee.com","SessionId",login);
                String result = wsWfzHrztFacade.insertBill("WFZ007", json);
                log.info("社保分摊同步eas结果；"+result);
                JSONObject reInfo = JSONObject.parseObject(result);
                String fState = reInfo.getString("FState");
                if ("1".equals(fState)){
                    //记录日志后续开发
                    wfzSbft.setFiseas((long)1);
                    wfzSbftService.updateWfzSbft(wfzSbft);
                    //将成功信息记录下来
                    succNum++;
                    buffer.append("<br/>" + succNum + "、数据 ID " + wfzSbft.getFid() + " 导入成功");
                }else {
                    //记录日志后续开发
//                    buffer.append(result);
                    failNum++;
                    buffer.append("<br/>" + failNum + "、数据 ID " + wfzSbft.getFid() + " 导入失败"+reInfo.getString("Fmessage"));

                }
            } catch (ServiceException e) {
                throw new RuntimeException(e);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }

            System.out.println(json);
        }
        if (failNum > 0){
            buffer.insert(0,"很抱歉，调用失败！共"+ failNum + "条数据调用失败，错误如下：");
        }else {
            buffer.insert(0,"所有的数据全部调用成功！共 "+succNum +" 条，数据如下：");
        }
        return AjaxResult.success(buffer.toString());
    }
}
